package com.finalterm.product.task;

import com.finalterm.product.service.ProductCacheService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 缓存清理定时任务
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CacheCleanupTask {
    
    private final ProductCacheService productCacheService;
    
    /**
     * 每5分钟清理一次过期缓存
     */
    @Scheduled(fixedRate = 300000) // 5分钟 = 300000毫秒
    public void cleanExpiredCache() {
        try {
            log.debug("开始清理过期商品缓存");
            productCacheService.cleanExpiredCache();
            log.debug("过期商品缓存清理完成");
        } catch (Exception e) {
            log.error("清理过期缓存失败：{}", e.getMessage(), e);
        }
    }
    
    /**
     * 每小时输出缓存统计信息
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void logCacheStats() {
        try {
            String stats = productCacheService.getCacheStats();
            log.info("商品缓存统计: {}", stats);
        } catch (Exception e) {
            log.error("获取缓存统计失败：{}", e.getMessage(), e);
        }
    }
}
